package vip.zhenzicheng.jvm.jvmbook.part2;

/**
 * 一个对象自我拯救的demo
 *
 * @author zhenzicheng
 * @date 2022-07-19 19:44
 */
public class FinalizeEscapeGC {

  public static FinalizeEscapeGC SAVE_HOOK = null;

  public void isAlive() {
    System.out.println("yes, i am still alive :)");
  }

  @Override
  protected void finalize() throws Throwable {
    super.finalize();
    System.out.println("finalize method executed!");
    FinalizeEscapeGC.SAVE_HOOK = this;
  }

  public static void main(String[] args) throws InterruptedException {
    SAVE_HOOK = new FinalizeEscapeGC();

    // 第一次尝试自我拯救
    SAVE_HOOK = null;
    System.gc();
    // 因为 Finalizer线程优先级很低，等待一会儿
    Thread.sleep(500);
    if (SAVE_HOOK != null) {
      SAVE_HOOK.isAlive();
    } else {
      System.out.println("no, i am dead :(");
    }

    // 第二次尝试自我拯救
    SAVE_HOOK = null;
    System.gc();
    // 因为 Finalizer线程优先级很低，等待一会儿
    Thread.sleep(500);
    if (SAVE_HOOK != null) {
      SAVE_HOOK.isAlive();
    } else {
      System.out.println("no, i am dead :(");
    }
  }
}
